package com.agile.leetcode.http.server;

import com.agile.leetcode.http.protocol.Request;
import com.agile.leetcode.http.protocol.Response;
import com.agile.leetcode.http.util.Encode;
import com.agile.leetcode.http.util.ProtocolUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/5/24 22:06
 */
public class Server {
    public static void main(String[] args) throws IOException {
        // 监听
        ServerSocket serverSocket = new ServerSocket(8081);
        //
        while (true) {
            Socket socket = serverSocket.accept();
            // 拿到输入流
            InputStream inputStream = socket.getInputStream();
            // 拿到请求对象
            Request request = ProtocolUtil.readRequest(inputStream);
            //
            System.out.println("收到的参数是==" + request);
            // 拿到输出溜
            OutputStream outputStream = socket.getOutputStream();
            // 封装数据
            Response response = new Response();
            response.setEncode(Encode.UTF8);
            if ("HELLO".equals(request.getCommand())) {
                response.setContent("HELLO,HELLO");
            } else {
                response.setContent("czk");
            }
            response.setCommandLength(response.getContent().length());
            ProtocolUtil.writeResponse(outputStream, response);
        }
    }
}
